package com.student.controller;


import com.student.dto.ResponseDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.InetAddress;
import java.util.UUID;

@RestController
public class FileUploadController {
    @Value("${uploadDir}")
    private String uploadDir;
    @Value("${server.port}")
    private String port;



    @PostMapping("image")
    public ResponseDto upload(@RequestBody MultipartFile file) {
        System.err.println(file);
        int i = file.getOriginalFilename().lastIndexOf(".");
//        获取后缀
        String suffix = file.getOriginalFilename().substring(i);
        System.out.println(suffix);
        if (file != null) {
            if (file.getContentType().equals("image/png") ||
                    file.getContentType().equals("image/jpg") ||
                    file.getContentType().equals("image/jpeg")) {
//                创建一个uuid
                UUID uuid = UUID.randomUUID();
                String path = uploadDir + "images/";
                File file1 = new File(path);
                if (!file1.exists()) {
//                    创建文件夹多级
                    file1.mkdirs();
                }
//
                File dest = new File(path + uuid + suffix);
                String url = "";
                try {
                    String hostAddress = InetAddress.getLocalHost().getHostAddress();
                    url = "http://127.0.0.1"  +":6060/images/" + uuid + suffix;
                    file.transferTo(dest);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return new ResponseDto(1,"上传成功" , url);

            } else {
                return new ResponseDto(2, "文件格式不对", null);
            }
        } else {
            return ResponseDto.error(null);
        }
    }
}